package ltd.ninefish.framework.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import ltd.ninefish.framework.core.constant.DatabaseConst;
import ltd.ninefish.framework.core.handler.SecurityContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author zhaoxiubin
 * create-time 2023-11-18 13:59
 * description 公共字段自动填充
 **/
@Slf4j
@Component
public class FieldMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime date = LocalDateTime.now();
        Long userId = SecurityContextHolder.getUserId();
        if (null != userId){
            //创建者
            strictInsertFill(metaObject, DatabaseConst.FIELD_CREATOR, Long.class, userId);
            //更新者
            strictInsertFill(metaObject, DatabaseConst.FIELD_UPDATER, Long.class, userId);
        }
        //创建时间
        strictInsertFill(metaObject, DatabaseConst.FIELD_CREATE_TIME, LocalDateTime.class, date);
        //更新时间
        strictInsertFill(metaObject, DatabaseConst.FIELD_UPDATE_TIME, LocalDateTime.class, date);
        //更新时间
        strictInsertFill(metaObject, DatabaseConst.LOGIC_DELETE_FIELD, Integer.class, DatabaseConst.LOGIC_NOT_DELETE_VALUE);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = SecurityContextHolder.getUserId();
        if (null != userId){
            //更新者
            strictUpdateFill(metaObject, DatabaseConst.FIELD_UPDATER, Long.class, userId);
        }
        //更新时间
        strictUpdateFill(metaObject, DatabaseConst.FIELD_UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }
}
